package com.zcsy.commons.util;


import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.imap.protocol.MailboxInfo;

import sun.misc.BASE64Encoder;


/**
 * @Title: MailUtils.java
 * @Package： com.zcsy.web.websocket
 * @Description: 发送邮件工具类〈一句话功能简述〉 〈功能详细描述〉
 * @author wangziliang 460694546@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2015年7月1日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
public class MailUtils {

    String to = "";// 收件人

    String from = "";// 发件人

    String host = "";// smtp主机

    String username = "";

    String password = "";

    String filename = "";// 附件文件名

    String subject = "";// 邮件主题

    String content = "";// 邮件正文

    Vector file = new Vector();// 附件文件集合

    public MailUtils() {

    }

    /**
     * @param to
     *            目的邮箱
     * @param from
     *            起始邮箱
     * @param smtpServer
     *            服务器
     * @param username
     *            用户名
     * @param password
     *            密码
     * @param subject
     *            主题
     * @param content
     *            正文内容
     */
    public MailUtils(String to, String from, String smtpServer, String username, String password,
                     String subject, String content) {
        this.to = to;
        this.from = from;
        this.host = smtpServer;
        this.username = username;
        this.password = password;
        this.subject = subject;
        this.content = content;
    }

    /**
     * @Description 设置主机<br>
     * @param host
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setHost(String host) {
        this.host = host;
    }

    /**
     * @Description 设置密码<br>
     * @param host
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setPassWord(String pwd) {
        this.password = pwd;
    }

    /**
     * @Description 设置用户名<br>
     * @param host
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setUserName(String usn) {
        this.username = usn;
    }

    /**
     * @Description 设置目的邮箱<br>
     * @param host
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setTo(String to) {
        this.to = to;
    }

    /**
     * @Description 设置发送邮箱<br>
     * @param host
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setFrom(String from) {
        this.from = from;
    }

    /**
     * @Description 设置主题<br>
     * @param host
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * @Description 设置内容正文<br>
     * @param content
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @Description 编码转换<br>
     * @param strText
     * @return
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public String transferChinese(String strText) {
        try {
            strText = MimeUtility.encodeText(new String(strText.getBytes(), "GB2312"), "GB2312",
                "B");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strText;
    }

    /**
     * @Description 添加附件<br>
     * @param fname
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public void attachfile(String fname) {
        file.addElement(fname);
    }

    /**
     * @Description 发送邮件<br>
     * @return
     * @author wangziliang 46094546@qq.com
     * @date 2015年7月1日
     * @see
     */
    public boolean sendMail() {

        // 构造mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            // 构造MimeMessage 并设定基本的值
            MimeMessage msg = new MimeMessage(session);
            // MimeMessage msg = new MimeMessage();
            msg.setFrom(new InternetAddress(from));

            // msg.addRecipients(Message.RecipientType.TO, address); //这个只能是给一个人发送email
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to));
            
            // 设置邮件消息的主题
            //使用Bese64编码邮件主题,防止乱码
            sun.misc.BASE64Encoder base64 = new BASE64Encoder();
            subject = new String(base64.encode(subject.getBytes("UTF-8")));
            msg.setSubject("=?UTF-8?B?" + subject + "?=");
//            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
            /*subject = transferChinese(subject);
            msg.setSubject(subject);*/

            // 构造Multipart
            Multipart mp = new MimeMultipart();

            // 向Multipart添加正文
            MimeBodyPart mbpContent = new MimeBodyPart();
            mbpContent.setContent(content, "text/html;charset=gb2312");

            // 向MimeMessage添加（Multipart代表正文）
            mp.addBodyPart(mbpContent);

            // 向Multipart添加附件
            Enumeration efile = file.elements();
            while (efile.hasMoreElements()) {

                MimeBodyPart mbpFile = new MimeBodyPart();
                filename = efile.nextElement().toString();
                FileDataSource fds = new FileDataSource(filename);
                mbpFile.setDataHandler(new DataHandler(fds));

                String filename = new String(fds.getName().getBytes(), "ISO-8859-1");

                mbpFile.setFileName(filename);
                // 向MimeMessage添加（Multipart代表附件）
                mp.addBodyPart(mbpFile);

            }

            file.removeAllElements();
            // 向Multipart添加MimeMessage
            msg.setContent(mp);
            msg.setSentDate(new Date());
            msg.saveChanges();
            // 发送邮件

            Transport transport = session.getTransport("smtp");
            transport.connect(host, username, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception mex) {
            mex.printStackTrace();
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        MailUtils sendmail = new MailUtils();
        sendmail.setHost("smtp.163.com");
        sendmail.setUserName("15392889506@163.com");
        sendmail.setPassWord("plkyesnpokyjyirg");
        sendmail.setTo("460694546@qq.com");
        sendmail.setFrom("15392889506@163.com");
        sendmail.setSubject("qwe");
        sendmail.setContent("");
        sendmail.attachfile("d:/fruit.jpg");
        sendmail.attachfile("d:/fruit.jpg");
        System.out.println(sendmail.sendMail());
    }
}
